<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入接口名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-table height="0" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template v-slot="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="接口名称" align="center" prop="name" />
      <el-table-column label="序列号" align="center" prop="serialNumber" />

      <el-table-column label="接口描述" align="center" prop="description" />

      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleShow(scope.row)"
            v-hasPermi="['system:dict:edit']"
          >查看</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDebug(scope.row)"-->
<!--            v-hasPermi="['system:dict:remove']"-->
<!--          >调试</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body center :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="接口名称">
          <el-input v-model="form.name" readOnly />
        </el-form-item>
        <el-form-item label="序列号" prop="serialNumber">
          <el-input v-model="form.serialNumber" readOnly />
        </el-form-item>
        <el-form-item label="接口描述" prop="dictValue">
          <el-input v-model="form.description" readOnly />
        </el-form-item>
        <el-form-item label="请求路径" prop="cssClass">
          <el-input v-model="form.requestUrl" readOnly />
        </el-form-item>

        <el-form-item label="请求方法" prop="requestMethod">
          <el-select v-model="form.requestMethod" disabled>
            <el-option
              v-for="item in requestMethodOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.usageStatus" disabled>
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请求头" prop="requestHeader">
          <el-input v-model="form.requestHeader" readOnly type="textarea" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" readOnly />
        </el-form-item>
        <el-form-item label="请求参数" prop="requestParams">
          <el-table
            :data="paramsData"
            style="width: 100%">
            <el-table-column prop="date" label="序号" width="80">
              <template v-slot="scope">{{scope.row.index}}</template>
            </el-table-column>
            <el-table-column prop="name" label="键">
              <template v-slot="scope">
                <el-input size="small" v-model="scope.row.key" type="text" :maxlength="20" readonly/>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="值">
              <template v-slot="scope">
                <el-input size="small" v-model="scope.row.value" type="text" :maxlength="100" readonly/>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" icon="el-icon-close">关 闭</el-button>
        <el-button type="primary" icon="el-icon-magic-stick" @click="debugHandle">调试</el-button>
      </div>
    </el-dialog>
    <!--调用结果-->
    <Result ref="resultPage"/>
  </div>
</template>

<script>
import axios from "axios";
import {listApiInfo,addApiInfo,updateApiInfo,delApiInfo,getApiInfo} from "@/api/model/apiCollection"
import Result from '@/views/model/use/model/Result'
export default {
  name: "apiCollection",
  components: { Result },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 默认字典类型
      defaultDictType: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据标签回显样式
      requestMethodOption: [
        {
          value: "GET",
          label: "GET"
        },
        {
          value: "POST",
          label: "POST"
        },

      ],
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      basicInfoId:undefined,
      // 表单校验
      rules: {
        // dictLabel: [
        //   { required: true, message: "数据标签不能为空", trigger: "blur" }
        // ],

      },
      paramsData:[],
    };
  },
  created() {
    // 模型基本信息表主键id
    const id = this.$route.params && this.$route.params.id;
    this.basicInfoId = id;
    this.getList(id);
  },
  methods: {
    /* 调试 */
    debugHandle() {
      this.open = false;
      this.$refs.resultPage.getResult();
    },
    /** 查询字典数据列表 */
    getList(id) {
      this.loading = true;
      this.queryParams['basicInfoId'] = id;
      listApiInfo(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        serialNumber: undefined,
        description: undefined,
        requestUrl: undefined,
        requestMethod: undefined,
        requestHeader: undefined,
        requestParams: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/model/info" };
      this.$tab.closeOpenPage(obj);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口信息";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictCode)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleShow(row) {
      this.reset();
      const id = row.id || this.ids
      getApiInfo(id).then(response => {
        this.form = response.data;
        this.paramsData = [{
          id: 0,
          index: 1,
          key: '人',
          value: ''
        }, {
          id: 1,
          index: 2,
          key: '物',
          value: ''
        }, {
          id: 2,
          index: 3,
          key: '环境',
          value: ''
        }, {
          id: 3,
          index: 4,
          key: '管理',
          value: ''
        }, {
          id: 4,
          index: 5,
          key: '任务',
          value: ''
        }]
        this.open = true;
        this.title = "查看接口信息";
      });
    },
    handleDebug(row){
      const {requestHeader,requestMethod,requestParams,requestUrl} = row;
      const headers = JSON.parse(requestHeader);
      const paramsArray = JSON.parse(requestParams);
      const obj = {};
      paramsArray.forEach((item)=>{
        const { key,value } = item;
        obj[key] = value;
      })
      const config = {
        headers,
        method: requestMethod,
        url: requestUrl,
        timeout: 3000,
        responseType: 'json',
      };
      if("GET" === requestMethod){
        config['params'] = obj;
      }else{
        config['data'] = obj;
      }
      console.log('config',config)
      axios.request(config).then(response =>{
        this.$message.success(response);
        console.log('响应成功结果',response);
      }).catch(error =>{
        this.$message.error(error);
        console.log('响应失败结果',error);
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除字典编码为"' + id + '"的数据项？').then(function() {
        return delApiInfo(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

  }
};
</script>
